from django.utils.translation import gettext_lazy, gettext as _
from rest_framework.permissions import IsAuthenticated
from rest_framework.serializers import Serializer
from rest_framework.response import Response
from rest_framework.decorators import action
from drf_yasg.utils import swagger_auto_schema

from core import errors
from utils.paginators import NoPaginatorInspector
from apps.api.paginations import NewPageNumberPagination100
from apps.api.viewsets import NormalGenericViewSet, serializer_error_msg
from apps.app_tx_meeting import serializers
from apps.app_tx_meeting.managers import MeetingUserWrapper, tx_meeting_configs


class ConfigsReserveTimesViewSet(NormalGenericViewSet):
    permission_classes = [IsAuthenticated]
    pagination_class = NewPageNumberPagination100
    lookup_field = 'id'

    @swagger_auto_schema(
        tags=['tx_meeting'],
        operation_summary=gettext_lazy('查询会议预定相关时间的配置'),
        paginator_inspectors=[NoPaginatorInspector],
        responses={
            200: ''''''
        }
    )
    def list(self, request, *args, **kwargs):
        """
        查询会议预定相关时间的配置，管理员权限

            http code 200:
            {
                "reserve_room_advance_minutes": 30，    # 提前（预定开始时间）多少分钟预留会议室资源
                "meeting_after_reserve_minutes": 60，    # 会议预定结束时间后，会议室资源多预留多少分钟
                "default_advance_notice_minutes": 30    # 默认提前多少分钟发送会议提醒通知
            }
        """
        ur_wrapper = MeetingUserWrapper(user=request.user)
        if not ur_wrapper.is_active_user():
            return self.exception_response(
                errors.AccessDenied(message=_('你的账号状态无效')))

        if not ur_wrapper.is_admin():
            return self.exception_response(
                errors.AccessDenied(message=_('你没有管理员权限')))

        tx_meeting_configs.clear_cache()
        return Response(data={
            'reserve_room_advance_minutes': int(
                tx_meeting_configs.get(tx_meeting_configs.ConfigName.RESERVE_ROOM_ADVANCE_MINUTTES.value)),
            'meeting_after_reserve_minutes': int(
                tx_meeting_configs.get(tx_meeting_configs.ConfigName.MEETING_AFTER_RESERVE_MINUTES.value)),
            'default_advance_notice_minutes': int(
                tx_meeting_configs.get(tx_meeting_configs.ConfigName.DEFAULT_ADVANCE_NOATICE_MINUTES.value))
        })

    @swagger_auto_schema(
        tags=['tx_meeting'],
        operation_summary=gettext_lazy('修改会议预定相关时间的配置'),
        paginator_inspectors=[NoPaginatorInspector],
        responses={
            200: ''''''
        }
    )
    @action(methods=['POST'], detail=False, url_path='update', url_name='update')
    def update_reserve_configs(self, request, *args, **kwargs):
        """
        修改会议预定相关时间的配置，管理员权限

            http code 200:
            {
                "reserve_room_advance_minutes": 30，    # 提前（预定开始时间）多少分钟预留会议室资源
                "meeting_after_reserve_minutes": 60，    # 会议预定结束时间后，会议室资源多预留多少分钟
                "default_advance_notice_minutes": 30    # 默认提前多少分钟发送会议提醒通知
            }
        """
        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid(raise_exception=False):
            msg = serializer_error_msg(serializer.errors)
            return self.exception_response(exc=errors.InvalidArgument(message=msg))

        data = serializer.validated_data
        reserve_room_advance_minutes = data.get('reserve_room_advance_minutes')
        meeting_after_reserve_minutes = data.get('meeting_after_reserve_minutes')
        default_advance_notice_minutes = data.get('default_advance_notice_minutes')

        ur_wrapper = MeetingUserWrapper(user=request.user)
        if not ur_wrapper.is_active_user():
            return self.exception_response(
                errors.AccessDenied(message=_('你的账号状态无效')))

        if not ur_wrapper.is_admin():
            return self.exception_response(
                errors.AccessDenied(message=_('你没有管理员权限')))

        if reserve_room_advance_minutes and reserve_room_advance_minutes >= 15:
            tx_meeting_configs.set(
                tx_meeting_configs.ConfigName.RESERVE_ROOM_ADVANCE_MINUTTES.value, str(reserve_room_advance_minutes))

        if meeting_after_reserve_minutes is not None and meeting_after_reserve_minutes >= 0:
            tx_meeting_configs.set(
                tx_meeting_configs.ConfigName.MEETING_AFTER_RESERVE_MINUTES.value, str(meeting_after_reserve_minutes))

        if default_advance_notice_minutes and default_advance_notice_minutes >= 15:
            tx_meeting_configs.set(
                tx_meeting_configs.ConfigName.DEFAULT_ADVANCE_NOATICE_MINUTES.value, str(default_advance_notice_minutes))

        tx_meeting_configs.clear_cache()
        return Response(data={
            'reserve_room_advance_minutes': int(
                tx_meeting_configs.get(tx_meeting_configs.ConfigName.RESERVE_ROOM_ADVANCE_MINUTTES.value)),
            'meeting_after_reserve_minutes': int(
                tx_meeting_configs.get(tx_meeting_configs.ConfigName.MEETING_AFTER_RESERVE_MINUTES.value)),
            'default_advance_notice_minutes': int(
                tx_meeting_configs.get(tx_meeting_configs.ConfigName.DEFAULT_ADVANCE_NOATICE_MINUTES.value))
        })

    def get_serializer_class(self):
        if self.action == 'update_reserve_configs':
            return serializers.ConfigsReserveTimesUpdateSerializer

        return Serializer
